package com.zhuiyun.project.api.groupmessage.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.ObjectUtil;
import com.tencentcloudapi.cfw.v20190904.models.TemplateListInfo;
import com.zhuiyun.project.api.appuser.entity.User;
import com.zhuiyun.project.api.appuser.mapper.AppUserMapper;
import com.zhuiyun.project.api.appuser.model.AppUserModel;
import com.zhuiyun.project.api.group.entity.Group;
import com.zhuiyun.project.api.group.service.GroupService;
import com.zhuiyun.project.api.groupmessage.entity.GroupMessage;
import com.zhuiyun.project.api.groupmessage.mapper.GroupMessageMapper;
import com.zhuiyun.project.api.groupmessage.model.GroupMessageModel;
import com.zhuiyun.project.api.groupmessage.service.GroupMessageService;
import com.zhuiyun.project.api.message.config.MessageType;
import com.zhuiyun.project.api.message.entity.Message;
import com.zhuiyun.project.api.message.service.MessageService;
import com.zhuiyun.project.api.messagelist.service.MessageListService;
import com.zhuiyun.project.api.personmessage.entity.PersonMessage;
import com.zhuiyun.project.api.personmessage.model.PersonMessageModel;
import com.zhuiyun.project.api.sysuser.entiy.SysUser;
import com.zhuiyun.project.api.sysuser.service.SysUserService;
import com.zhuiyun.project.api.sysuser.mapper.SysUserMapper;
import com.zhuiyun.project.api.sysuser.model.SysUserModel;
import com.zhuiyun.project.common.response.CommonResult;
import com.zhuiyun.project.util.BeanUtils;
import com.zhuiyun.project.util.pageUtil.MybatisPageHelper;
import com.zhuiyun.project.util.pageUtil.PageRequest;
import com.zhuiyun.project.util.pageUtil.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @ClassName GroupMessageServiceImpl
 * @Description TODO
 * @Author kdj
 * @Date 2023/7/24 19:50
 **/
@Service
public class GroupMessageServiceImpl implements GroupMessageService {
    @Autowired
    private GroupMessageMapper groupMessageMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private MessageService messageService;
    @Autowired
    private MessageListService messageListService;
    @Autowired
    private GroupService groupService;
    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private AppUserMapper appUserMapper;

    /**
     * @param userId
     * @param groupId
     * @param type
     * @Author kdj
     * @Description 根据群聊 群聊号 用户类型获取群聊列表消息
     * @Date 2023/7/25 10:30
     * @Return com.zhuiyun.project.common.response.CommonResult
     */
    @Override
    public List<Map> getGroupChat(int userId, int groupId, int type,PageRequest pageRequest) {


        //先把groupNum的数据取出来
        List<GroupMessageModel> chatList = groupMessageMapper.getGroupChatListById(groupId);
        //拦截掉 以及删除的
        //map结构：toId，fromId,createTime,content,msgType

        String typeText = type == MessageType.socketSysNum ? MessageType.socketSys : MessageType.socketApp;
        String targetUserId = typeText + "_" + userId;

        List<Map> mapList = chatList.stream()
                .filter(groupMessageModel -> {
                    String deleteUserId = groupMessageModel.getDeleteUserId();
                    return deleteUserId == null || !deleteUserId.contains(targetUserId);
                }) .map(GroupMessageServiceImpl::getMap)
                .collect(Collectors.toList());
        return mapList;
    }

    /**
     * @param groupMessageModel
     * @Author kdj
     * @Description 添加群聊消息
     * @Date 2023/7/25 16:29
     * @Return int
     */
    @Override
    public int insertGroupMsg(GroupMessageModel groupMessageModel) {
        //判断对象是否为空
        if (ObjectUtil.isNotEmpty(groupMessageModel)) {
            GroupMessage groupMessage = new GroupMessage();
            BeanUtils.copy(groupMessageModel, groupMessage);
            groupMessage.setUserType(groupMessageModel.getFromType());
            //添加到message表中  类型：单聊
            int messageId = messageService.insertMsg(new Message(groupMessageModel.getUuid(), MessageType.GroupMsgType));
            groupMessage.setMessageId(messageId);
            //默认 数据
            groupMessage.setDelFlag(0);
            groupMessage.setIsWithdraw(0);
            //最后聊天信息
            groupMessage.setCreateTime(new Date());
            groupMessage.setUpdateTime(new Date());
            groupMessageMapper.insertSelective(groupMessage);
            //修改messageList
            messageListService.updateChatList(messageId);
            return groupMessage.getId();
        }
        return 0;
    }

    /**
     * @param userId
     * @param groupId
     * @param type
     * @Author kdj
     * @Description 获取群聊最后一条消息 针对自己
     * @Date 2023/7/26 8:40
     * @Return com.zhuiyun.project.api.groupmessage.model.GroupMessageModel
     */
    @Override
    public Map getGroupChatLast(int userId, int groupId, int type) {
        List<GroupMessageModel> chatList = groupMessageMapper.getGroupChatListById(groupId);
        //拦截掉 以及删除的
        //map结构：toId，fromId,createTime,content,msgType

        String typeText = type == MessageType.socketSysNum ? MessageType.socketSys : MessageType.socketApp;
        String targetUserId = typeText + "_" + userId;
        for (GroupMessageModel groupMessageModel : chatList) {
            String deleteUserId = groupMessageModel.getDeleteUserId();
            if (deleteUserId == null || !deleteUserId.contains(targetUserId)) {
                return getMap(groupMessageModel) ;
            }
        }
        Group groupByGroupId = groupService.getGroupByGroupId(groupId);
        Map map = new HashMap();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = simpleDateFormat.format(groupByGroupId.getCreateTime());
        map.put("createTime", time);
        map.put("content", null);
        return map;
    }

    /**
     * @param groupId
     * @Author kdj
     * @Description 获取群聊最后一条消息 针对所有人
     * @Date 2023/7/26 16:23
     * @Return java.util.Map
     */
    @Override
    public GroupMessageModel getGroupChatLast(int groupId) {
        //判断该是不是撤回了
        GroupMessageModel groupChatLast = groupMessageMapper.getGroupChatLast(groupId);
        if (groupChatLast != null && groupChatLast.getIsWithdraw() == 1) {
            groupChatLast.setContent("该消息被撤回了！");
        }
        return groupChatLast;
    }

    /**
     * @param userId
     * @param groupId
     * @param type
     * @param pageRequest
     * @Author kdj
     * @Description 根据群聊 群聊号 用户类型获取群聊列表消息 分页
     * @Date 2023/7/29 17:12
     * @Return com.zhuiyun.project.util.pageUtil.PageResult
     */
    @Override
    public PageResult getGroupChatSys(int userId, int groupId, int type, PageRequest pageRequest, String time) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date;
        try {
            date = simpleDateFormat.parse(time);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }

        MybatisPageHelper.startPage(pageRequest);
        List<GroupMessageModel> chatList = groupMessageMapper.getGroupChatListByIdDesc(groupId, date);

        String typeText = type == MessageType.socketSysNum ? MessageType.socketSys : MessageType.socketApp;
        String targetUserId = typeText + "_" + userId;

        List<Map> mapList = chatList.stream()
                .filter(groupMessageModel -> {
                    String deleteUserId = groupMessageModel.getDeleteUserId();
                    return deleteUserId == null || !deleteUserId.contains(targetUserId);
                }) .map(GroupMessageServiceImpl::getMap)
                .collect(Collectors.toList());

        List<Map> reverse = ListUtil.reverse(mapList);
        PageResult pageResult = MybatisPageHelper.getPageResult(reverse);
        return pageResult;

    }

    /**
     * @param groupId
     * @param userId
     * @Author kdj
     * @Description 清除未读数
     * @Date 2023/7/29 20:37
     * @Return int
     */
    @Override
    public int cleanUnReadMsg(int groupId, int userId) {
        messageListService.upMsgListUmReadZero(groupId, userId, MessageType.GroupMsgType, 0, false);
        return 1;
    }

    @Override
    public int upDelMsg(GroupMessage groupMessage, int fromId,int chatType) {

        String delUser = chatType == MessageType.socketAppNum?MessageType.socketApp:MessageType.socketSys + "_" + fromId;
        //判断该消息是否被删除过;
        String deleteUserId = groupMessage.getDeleteUserId();
        if (deleteUserId != null && deleteUserId.contains(",")) {
            String[] split = deleteUserId.split(",");
            if (split.length == 0) {
                return 0;
            }
            for (String s : split) {
                String id = String.valueOf(s);
                if (id.equals(delUser)) {
                    return 0;
                }
            }
        }
        //之前没修改过
        deleteUserId = deleteUserId != null ? deleteUserId : "";
        //修改
        // 将 fromId 转换为字符串，并添加到 deleteUserId 后面
        String updatedDeleteUserId = deleteUserId + delUser + ",";

        // 修改
        groupMessage.setDeleteUserId(updatedDeleteUserId);
        return groupMessageMapper.upDelMsg(groupMessage.getDeleteUserId(), groupMessage.getId());
    }

    /**
     * @param groupMessageModel
     * @Author kdj
     * @Description 撤回消息
     * @Date 2023/7/31 15:29
     * @Return int
     */
    @Override
    @Transactional
    public int recallMsg(GroupMessageModel groupMessageModel) {

        //根据uuid找到该消息
        String uuid = groupMessageModel.getUuid();
        GroupMessage msgByUuid = groupMessageMapper.getMsgByUuid(uuid);
        //修改该对象的撤回标识为1
        msgByUuid.setIsWithdraw(1);
        //判断当前消息是不是app用户 如果是的话就修改msgList为0
        if (groupMessageModel.getUserType() == MessageType.socketAppNum) {
            msgByUuid.setWithdrawUserId(0);
            //修改messageList的未读数
            messageListService.upMsgListUmReadZero(groupMessageModel.getToId(), groupMessageModel.getFromId(), MessageType.GroupMsgType, 1, false);
        } else if (groupMessageModel.getFromId() == msgByUuid.getFromId()) {
            //判断是否为系统用户 判断当前群消息的发送者是否为该系统用户 //如果是的话 修改者为0
            msgByUuid.setWithdrawUserId(0);
        } else {
            //反之 为1
            msgByUuid.setWithdrawUserId(1);
        }
        groupMessageMapper.updateByPrimaryKeySelective(msgByUuid);
        //判断这个消息是不是最后一条
        Boolean b = isLast(msgByUuid);
        //修改msgList
        if (b) {
            messageListService.upMsgGroupListByRecall(msgByUuid);
        }
        return msgByUuid.getId();
    }

    /**
     * @param groupMessage
     * @Author kdj
     * @Description 根据groupMsg对象找到发送者名字
     * @Date 2023/7/31 16:31
     * @Return java.lang.String
     */
    @Override
    public String getFromName(GroupMessage groupMessage) {
        //判断格式
        Integer userType = groupMessage.getUserType();
        if (userType == MessageType.socketAppNum) {
            //从app中查询
            return appUserMapper.queryGroupUser(groupMessage.getFromId()).getUserName();
        }
        return sysUserService.getSysUserById(groupMessage.getFromId()).getUserName();
    }

    /**
     * @param fromId
     * @param toId
     * @Author kdj
     * @Description 获取单聊聊天内容中最后一条消息（删除之后）
     * @Date 2023/7/31 12:07
     * @Return com.zhuiyun.project.api.groupmessage.entity.GroupMessage
     */
    @Override
    public GroupMessage getMsgLastInfo(Integer fromId, Integer toId, int userId) {
        int open = 1;
        int size = 10;
        GroupMessageModel groupMessageModel = getGroupMessageModel(fromId, toId, open, size, userId);
        if (groupMessageModel == null) {
            return null;
        }
        GroupMessage groupMessage = new GroupMessage();
        BeanUtils.copy(groupMessageModel, groupMessage);
        return groupMessage;
    }


    /**
     * @param groupMessageModel
     * @Author kdj
     * @Description 将Msg格式转为单聊websocket中的格式
     * @Date 2023/7/21 18:20
     * @Return java.util.Map
     */
    private static Map getMap(GroupMessageModel groupMessageModel) {
        Map map = new HashMap<>();
        map.put("toId", groupMessageModel.getToId());
        map.put("fromId", groupMessageModel.getFromId());
        map.put("fromName", groupMessageModel.getFromName());
        map.put("fromImgId", groupMessageModel.getFromImgId());
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = simpleDateFormat.format(groupMessageModel.getCreateTime());
        map.put("createTime", time);
        map.put("content", groupMessageModel.getContent());
        map.put("chatType", MessageType.GroupMsgType);
        map.put("fromType", groupMessageModel.getUserType());
        map.put("uuid", groupMessageModel.getUuid());
        map.put("isWithdraw", groupMessageModel.getIsWithdraw() == 0 ? false : true);
        map.put("withdrawUserId", groupMessageModel.getWithdrawUserId() );
        String msgType = null;
        switch (groupMessageModel.getMsgType()) {
            case 0:
                msgType = "text";
                break;
            case 1:
                msgType = "image";
                break;
            case 2:
                msgType = "video";
                break;
            case 3:
                msgType = "other";
                break;
            case 4:
                msgType = "link";
                break;
        }
        map.put("msgType", msgType);
        return map;
    }

    /**
     * @param groupMessage
     * @Author kdj
     * @Description 判断这个对象是不是最后一条消息
     * @Date 2023/7/31 16:58
     * @Return int
     */
    @Override
    public Boolean isLast(GroupMessage groupMessage) {
        int lastId = groupMessageMapper.isLast(groupMessage);
        if (lastId == groupMessage.getId()) {
            return true;
        }
        return false;
    }

    /**
     * @param fromId
     * @param toId
     * @param open
     * @param size
     * @Author kdj
     * @Description 获取最后一个消息
     * @Date 2023/7/31 11:46
     * @Return com.zhuiyun.project.api.personmessage.model.PersonMessageModel
     */
    private GroupMessageModel getGroupMessageModel(int fromId, int toId, int open, int size, int userId) {
        //查询单聊的聊天记录
        List<GroupMessageModel> groupMessages = groupMessageMapper.getChatRecordLimit(fromId, open, size);

        //使用stream得到最后一个没被删除的消息
        GroupMessageModel groupMessageModel1 = null;
        for (GroupMessageModel groupMessage : groupMessages) {
            String deleteUserId = groupMessage.getDeleteUserId();
            if (deleteUserId == null) {
                // 取出该值
                groupMessageModel1 = groupMessage;
                break;
            } else if (deleteUserId != null && deleteUserId.contains(",")) {
                String[] split = deleteUserId.split(",");
                for (String s : split) {
                    String typeText = MessageType.socketApp;
                    if (s.equals(typeText + "_" + userId)) {
                        groupMessageModel1 = groupMessage;
                        break;
                    }
                }
            }
        }
        //判断personMessages的数量》10  就继续递归 并且
        //判断personMessageModel1还是不是null如果是的话open继续
        // 判断递归终止条件：如果消息数量小于等于10或找到了未删除的消息，则不再递归
        if (groupMessages.size() <= 10 || groupMessageModel1 != null) {
            return groupMessageModel1;
        } else {
            // 继续递归并更新open的值
            return getGroupMessageModel(fromId, toId, open + 1, size, userId);
        }
    }
}
